package com.heima.behavior.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.heima.behavior.service.ApBehaviorService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.constants.HotArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.dtos.ReadBehaviorDto;
import com.heima.model.behavior.dtos.UnLikeBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ApBehaviorServiceImpl implements ApBehaviorService {

    @Autowired
    private CacheService cacheService;

    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    //文章行为：点赞 & 取消点赞
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        if ( dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser apUser = AppThreadLocalUtil.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        UpdateArticleMess updateArticleMess = new UpdateArticleMess();
        updateArticleMess.setArticleId(dto.getArticleId());
        updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.LIKES);

        String articleIdKey = BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId();
        String hashKey = apUser.getId().toString();
        String jsonValue = JSONObject.toJSONString(dto);
        if (dto.getOperation() == 0) {
            if (cacheService.hGet(articleIdKey,hashKey) == null) {  //未点赞
                log.info("保存点赞数据：文章Id key {}，用户Id {}，请求json串 {}",dto.getArticleId(),hashKey,jsonValue);
                cacheService.hPut(articleIdKey,hashKey,jsonValue);
                updateArticleMess.setAdd(1);
            } else {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"已点赞");
            }
        } else {
            log.info("删除点赞数据：文章Id key {}，用户Id {}，请求json串 {}",dto.getArticleId(),hashKey,jsonValue);
            cacheService.hDelete(articleIdKey,hashKey);
            updateArticleMess.setAdd(-1);
        }

        //发送消息，数据聚合
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(updateArticleMess));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    //文章行为：文章阅读次数统计
    @Override
    public ResponseResult read(ReadBehaviorDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser apUser = AppThreadLocalUtil.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        String articleIdKey = BehaviorConstants.READ_BEHAVIOR + dto.getArticleId();
        String hashKey = apUser.getId().toString();
        String dtoJsonStr = (String)cacheService.hGet(articleIdKey, hashKey);

        if (StringUtils.isNotBlank(dtoJsonStr)) {
            ReadBehaviorDto readBehaviorDto = JSON.parseObject(dtoJsonStr, ReadBehaviorDto.class);
            readBehaviorDto.setCount(dto.getCount() + readBehaviorDto.getCount());  //更新阅读次数
            dtoJsonStr = JSONObject.toJSONString(readBehaviorDto);
        }

        log.info("保存用户阅读文章数据：文章Id key {}，用户Id {}，请求json串 {}", dto.getArticleId(), hashKey, dtoJsonStr);
        cacheService.hPut(articleIdKey, hashKey, dtoJsonStr);

        //发送消息，数据聚合
        UpdateArticleMess updateArticleMess = new UpdateArticleMess();
        updateArticleMess.setArticleId(dto.getArticleId());
        updateArticleMess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        updateArticleMess.setAdd(1);
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(updateArticleMess));

        return ResponseResult.okResult(AppHttpCodeEnum.NO_ALERT_INFO);
    }

    @Override
    public ResponseResult unLike(UnLikeBehaviorDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser apUser = AppThreadLocalUtil.getUser();
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        String articleIdKey = BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId();
        String hashKey = apUser.getId().toString();
        if (dto.getType() == 0) {
            log.info("保存用户不喜欢文章数据：文章Id key {}，用户Id {}，请求json串 {}", dto.getArticleId(), hashKey, JSON.toJSONString(dto));
            cacheService.hPut(articleIdKey,hashKey, JSON.toJSONString(dto));
        } else {
            log.info("删除用户不喜欢文章数据：文章Id key {}，用户Id {}，请求json串 {}", dto.getArticleId(), hashKey, JSON.toJSONString(dto));
            cacheService.hDelete(articleIdKey,hashKey);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.NO_ALERT_INFO);
    }
}
